package com.qf.petmall.starter.controller;
import com.qf.petmall.starter.entity.Order;
import com.qf.petmall.starter.service.IOrderService;
import com.qf.petmall.starter.service.IShopCartService;
import com.qf.petmall.starter.utils.OrderConstants;
import com.qf.petmall.starter.utils.R;
import com.qf.petmall.starter.utils.WxpayUtils;
import com.qf.petmall.starter.websockets.WebSocketServer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-12-08
 */
@Api(tags="订单模块")
@RestController
@RequestMapping("/order")
public class OrderController {
	@Autowired
	IOrderService orderService;

	@Autowired
	IShopCartService shopCartService;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	//添加订单
	@ApiOperation(value = "添加订单接口")
	@PostMapping("/add")
	public R add( @RequestBody Order order ) {
		//生成订单编号
		String orderId=OrderConstants.getOrderId( );
		order.setOrderId( orderId );

		//设置支付状态
		order.setOrderStatus( OrderConstants.ORDER_WAIT_TO_PAY );

		//生成下单时间
		order.setOrderTime( new Date( ) );

		boolean save=orderService.save( order );
		if (save) {
			//删除购物车里面的消息
			List< Integer > shopCartIds=order.getShopCartIds( );
			shopCartService.removeByIds( shopCartIds );
			return R.ok().put( "orderId",orderId );
		}
		return R.error();
	}

	//支付接口
	@ApiOperation(value = "调用支付接口")
	@GetMapping("/pay")
	public R payOrder( String orderId) throws Exception {
		//查询订单金额
		Order order=orderService.getById( orderId );

		//调用微信支付接口
		String payUrl=WxpayUtils.getPayUrl( orderId,"这是谁家的订单啊！！！" );

		//返回url

		return R.ok().put( "payUrl",payUrl );

	}

	//支付成功的回调函数
	@ApiOperation(value = "支付成功回调接口")
	@RequestMapping("/callback")
	public R callBack(String orderId){
		rabbitTemplate.convertAndSend("boot-topic-exchange","message","下单成功支付成功！");
		WebSocketServer.sendMsg( orderId,"1" );
		Order order=new Order( );
		order.setOrderStatus( OrderConstants.PAY_OK_STATUS );
		order.setOrderId( orderId );
		orderService.updateById( order );
		return  R.ok();
	}
}
